package com.weilus.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.stream.Collectors;


@Component
@Aspect
public class ValidAdvice {

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
    public void restControllerPointcut() {}

    @Around("restControllerPointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        for(Object arg : joinPoint.getArgs()){
            if(arg instanceof BindingResult){
                if (((BindingResult)arg).hasErrors()){
                    return ((BindingResult)arg).getFieldErrors()
                            .stream()
                            .collect(Collectors.toMap(
                                    FieldError::getField,
                                    FieldError::getDefaultMessage
                            ));
                }
            }
        }
        return joinPoint.proceed(joinPoint.getArgs());
    }

}
